package com.hl.sfzy.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import com.hl.sfzy.entity.Test;
import com.hl.sfzy.utils.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;



@RestController
public class TestController {
    
    @GetMapping("/hello")
    public R<Test> getMethodName() {
        Test test = new Test();
        test.setDate(new Date());
        return R.success(test);
        
    }

    /**
     * 测试文件下载
     * @param response
     * @return
     * @throws IOException
     */

    @GetMapping("downtest")
    public void down(HttpServletResponse response,String fileName) throws IOException {
        // 原生servlet
        File file = new File(fileName);
        InputStream inputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        FileCopyUtils.copy(inputStream, outputStream);
    }

    @GetMapping("downmvc")
    public ResponseEntity<UrlResource> filedownMVC() throws MalformedURLException {
        String fileName = "hello.jpg";
        Path path = Paths.get("/Users/firefly/Downloads/"+fileName);
        UrlResource urlResource = new UrlResource(path.toUri());
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + urlResource.getFilename() + "\"").body(urlResource);
    }
    
    
}
